#include<stdio.h>
#include<stdlib.h>
#define nullptr NULL 
typedef struct ListNode {
    int val;
    struct ListNode *next;
}ListNode;

ListNode* partition(ListNode* pHead, int x)
{
    ListNode* LessHead = nullptr, * GreaterHead = nullptr;
    ListNode* LessTail = nullptr, * GreaterTail = nullptr;
    ListNode* cur = pHead;
    while (cur)
    {
        if (cur->val < x)
        {
            if (LessTail == nullptr)
            {
                LessHead = LessTail = cur;
            }
            else
            {
                LessTail->next=cur;
                LessTail = LessTail->next;
            }
            cur = cur->next;
        }
        else
        {
            if (GreaterTail == nullptr)
            {
                GreaterHead = GreaterTail = cur;
            }
            else
            {
                GreaterTail->next = cur;
                GreaterTail = GreaterTail->next;
            }
            cur = cur->next;
        }
    }
    if (GreaterTail == nullptr)
    {
        return LessHead;
    }

    GreaterTail->next = nullptr;
    if (LessTail == nullptr)
    {
        pHead = GreaterHead;
        return  pHead;
    }

    LessTail->next = GreaterHead;
    pHead = LessHead;
    return pHead;
}


int main()
{
    struct ListNode* n1 = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* n2 = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* n3 = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* n4 = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* n5 = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* n6 = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* n7 = (struct ListNode*)malloc(sizeof(struct ListNode));
    n1->val = 1;
    n2->val = 5;
    n3->val = 7;
    n4->val = 3;
    n5->val = 9;
    n6->val = 8;
    n7->val = 2;
    n1->next = n2;
    n2->next = n3;
    n3->next = n4;
    n4->next = n5;
    n5->next = n6;
    n6->next = n7;
    n7->next = NULL;
    printf("%d ", n1->val);
    printf("%d ", n1->next->val);
    printf("%d ", n1->next->next->val);
    printf("%d ", n1->next->next->next->val);
    printf("%d ", n1->next->next->next->next->val);
    printf("%d ", n1->next->next->next->next->next->val);
    printf("%d ", n1->next->next->next->next->next->next->val);
    printf("\n");
    ListNode* newhead = partition(n1, 0);
    printf("%d ", newhead->val);
    printf("%d ", newhead->next->val);
    printf("%d ", newhead->next->next->val);
    printf("%d ", newhead->next->next->next->val);
    printf("%d ", newhead->next->next->next->next->val);
    printf("%d ", newhead->next->next->next->next->next->val);
    printf("%d ", newhead->next->next->next->next->next->next->val);
   
    return 0;
    
}